var objOrg = null
var objWfRole = null
var topOrgList = []
var wfRoleUserList_obj = []
var wfRoleUserList_id = []
var dst = '#ouTree'
var authtree, form, layer, table
var treeList = null
var tempTitle, tempUrl

layui.config({
    base: '/static/lib/layuiadmin/modules/',
}).extend({
    authtree: '/authtree_zimi',
}).use(['jquery', 'authtree_zimi', 'form', 'layer', 'table'], function () {
    authtree = layui.authtree_zimi;
    form = layui.form;
    layer = layui.layer;
    table = layui.table;

    initData()
    form.render()

    table.render({
        elem: '#wfRole'
        ,height: 'full-188'
        ,url: "/wf-role/selectList"
        ,response: {
            statusCode: 200
            ,dataName: 'List'
        }
        ,limit: 9999
        ,cols:  [[
            ,{title: '序号', width:40, type:'numbers'}
            ,{field: 'enName', title: '角色标识', width:140, sort: true}
            ,{field: 'cnName', title: '角色名称', width:200, sort: true}
            ,{field: 'createTime', title: '创建时间', width:160, sort: true}
            ,{title: '操作', width:113, align: 'center', templet: function (e) {
                if (e.state == 9) {
                    return "<span title='禁止删改'>--系统角色--</span>"
                }

                return "<a class=\"layui-btn layui-btn-xs\" lay-event=\"edit\">编辑</a>\n" +
                    "    <a class=\"layui-btn layui-btn-danger layui-btn-xs\" lay-event=\"del\">删除</a>"

            }}
        ]],
        done: function () {
            $("div[lay-id=\"wfRole\"]").find("th").css("text-align","center")
        }
    });

    table.render({
        elem: '#wfRoleUser'
        ,height: 'full-248'
        ,data: []
        ,limit: 9999
        ,cols: [[ //表头
            {title: '序号', width:40, type:'numbers'}
            ,{field: 'name', title: '姓名', width:100, sort:true}
            ,{field: 'postName', title: '岗位', width:290}
            // ,{title: '操作', width:84, toolbar: '#toolRoleUser'}
            ,{title: '操作', width:84, toolbar: '#toolRoleUser'}
        ]],
        done: function () {
            $("div[lay-id=\"wfRoleUser\"]").find("th").css("text-align","center")
        }
    });

    form.on('select(orgSelect)', function(data){

        if (data.value) {
            objOrg = JSON.parse(data.value.replace(/'/g, "\""))
        } else {
            objOrg = null
            objWfRole = null
            wfRoleUserList_id.length = 0
            wfRoleUserList_obj.length = 0
        }
        $("#msgSelectRole").css("display", "")

        renderRoleTable()
        renderRoleUserTable()
        renderTree()
        disableTree()

    });

    table.on('tool(wfRole)', function(obj){

        var data = obj.data;
        var layEvent = obj.event;
        var tr = obj.tr;

        if(layEvent === 'edit'){
            addRole(obj.data)
        } else if(layEvent === 'del'){
            layer.confirm('确认删除该角色？', function(index){
                if ( delRole(obj) )  {
                    objWfRole = null
                    disableTree()
                    obj.del()
                }
                layer.close(index);
            });
        }
    });

    //监听行工具事件
    table.on('tool(wfRoleUser)', function(obj){
        var rowData = obj.data;
        if(obj.event === 'moveout'){
            // console.log(obj)
            var iRm = wfRoleUserList_id.indexOf(rowData.id)
            var iRmName = wfRoleUserList_obj[iRm].name

            wfRoleUserList_id.splice(iRm,1)
            wfRoleUserList_obj.splice(iRm,1)
            obj.del()

            $("input[state='5'][title=" + iRmName + "]").each(function (i, iDom) {
                if ($(iDom).next().hasClass("layui-form-checked")) {
                    $(iDom).click()
                }
            })

            form.render()
        }
    });

    table.on('row(wfRole)', function(obj){

        $("div[lay-id=\"wfRole\"]").find(".layui-table-click").removeClass("layui-table-click")
        obj.tr.addClass("layui-table-click")

        objWfRole = obj.data

        loadRoleUserData()
        renderRoleUserTable()
        enableTree()
        renderTreeChecked()
    });

});

function addRole(itype) {
    if (!objOrg) return

    if (itype == 0) {
        tempTitle = "添加角色"
        tempUrl = "/wf-role/addWfRole"
        objWfRole = null
    } else {
        tempTitle = "编辑角色"
        tempUrl = "/wf-role/updateWfRole"
        objWfRole = itype
    }

    layer.open({
        type: 1
        , content: $('#divAddRole')
        , resize: false
        , area: ['500px', '350px']
        , title: tempTitle
        , success: function (layero, index) {   //弹出后回调
            $('#orgId').val(objOrg.orgName)

            if (itype) {
                $('#enName').val(objWfRole.enName)
                $('#cnName').val(objWfRole.cnName)
                $('#description').val(objWfRole.description)
            }
        }
        , end: function () {    //销毁后回调
            $('#divAddRole').css('display', 'none')

            $('#orgId').val("")
            $('#enName').val("")
            $('#cnName').val("")
            $('#description').val("")
        }
    });
}

function delRole(objData) {
    var returnBool = false


    $.ajax({
        url: "/wf-role/delWfRole",
        data: {
            id: objData.data.id
        },
        type: 'post',
        async: false,
        success: function (res) {
            // console.log(res)
            if (res.OK == "OK") {
                returnBool = true
                layer.msg("删除成功！")
            } else {
                if (res.code == 90001) {
                    layer.msg("请先移除角色包含的用户！")
                }
            }
        },
        error: function (e) {
            console.log(e)
        }
    });

    return returnBool
}

function initData() {
    ActHttpRequest('/wf/activity/authority/userTree', {}, function (resData) {
        if (resData.code != 0) return
        // console.log(resData)
        treeList = formatData(resData.data, 'parentId', 'id', 'name', 'choiceFlag');

        renderOrgSelect()


        form.on('checkbox(chkUser)', function (thisData) {
            // 注意这里：需要等待事件冒泡完成，不然获取叶子节点不准确。

            wfRoleUserList_obj.length = 0
            wfRoleUserList_id.length = 0
            setTimeout(function () {
                var leaf = authtree.getLeaf('#ouTree');
                var lastChecked = authtree.getLastChecked('#ouTree');
                var lastNotChecked = authtree.getLastNotChecked('#ouTree');

                leaf.forEach(function (item) {
                    if (item.replace(/.*'flag':([1|3|5]).*/,'$1')=='5') {
                        var i = JSON.parse(item.replace(/'/g, "\""))
                        if (wfRoleUserList_id.indexOf(i.id) < 0) {
                            wfRoleUserList_id.push(i.id)
                            wfRoleUserList_obj.push(i)
                        }
                    }
                })

                renderRoleUserTable()

            }, 100);
        });


    }, 'post', null, null, '保存中。。。', false);

}

/**
 * 数据封装
 * @param data 数据
 * @param pid  父ID
 * @param id  ID
 * @param name 显示名称
 * @param checked 选中状态
 */
function formatData(values, pid, id, name, checked) {
    var tree = [],
        item,
        obj;

    var orgMap = new Map();
    var postMap = new Map();
    var hasChildPost = new Map();
    userMap = new Map();


    // 1)变格式保存到Map
    for (var i = 0; i < values.length; i++) {
        item = new Object();
        // if (values[i].flag == 5 && returnObj.ids.indexOf(values[i].id) > -1) {
        //     values[i][checked] = true;
        // }

        item.value = JSON.stringify(values[i]).replace(/"/g, "'");
        item.name = values[i][name];
        item.type = values[i].flag;
        item.checked = values[i][checked];
        item.list = [];

        switch (values[i].flag) {
            case 1:
                orgMap.set(values[i][id], item);

                if (values[i][pid] == 0) {
                    tree.push(item);
                    topOrgList.push(item)
                }

                break;
            case 3:
                postMap.set(values[i].orgId + '-' + values[i][id], item);
                break;
            case 5:
                userMap.set(values[i][id], item);
                hasChildPost.set(values[i].orgId + '-' + values[i].postId, "1")
                break;
        }
    }

    var strOrgPost = ""
    // 2)作为子项目加到父项目的list
    for (var i = 0; i < values.length; i++) {
        switch (values[i].flag) {
            case 1:
                if (values[i][pid] > 0) {
                    obj = orgMap.get(values[i][pid]);
                    obj.list.push(orgMap.get(values[i][id]));
                }
                break;
            case 3:
                obj = orgMap.get(values[i][pid]);

                strOrgPost = values[i].orgId + '-' + values[i][id]

                if (hasChildPost.has(strOrgPost)) {
                    obj.list.push(postMap.get(strOrgPost));
                }

                break;
            case 5:
                obj = postMap.get(values[i].orgId + '-' + values[i].postId);

                if (obj){
                    obj.list.push(userMap.get(values[i][id]));
                }
                break;
        }
    }

    // 3)删除没有子项目的list
    for (var i = 0; i < tree.length; i++) {
        removeChild(tree[i]);
    }

    return tree;
}

function removeChild(obj) {
    if (obj.hasOwnProperty('list')) {
        if (obj.list.length > 0) {
            if (obj.list.length == 1 && obj.type == 1) {
                delete obj.list;
            } else {
                for (var i = obj.list.length - 1; i >= 0; i--) {
                    removeChild(obj.list[i]);
                }
            }
        } else {
            delete obj.list;
        }
    }
}

function renderOrgSelect() {
    if (topOrgList.length < 1) return;
    var orgSelect = $("select[lay-filter='orgSelect']")

    topOrgList.forEach(function (iorg) {
        orgSelect.append("<option value=" + iorg.value + ">" + iorg.name + "</option>")
    })
}

function closeLayer(layerIndex) {
    if (layerIndex) {
        layer.close(layerIndex);
    } else {
        layer.closeAll()
    }
}

function saveRole() {
    var roleData=$("#formRoleInfo").serializeJSON();
    roleData.orgId = objOrg.id

    if (objWfRole) {
        roleData.id = objWfRole.id
    }

    $.ajax({
        url: tempUrl,
        data: roleData,
        type: 'post',
        success: function (res) {
            if (res.OK == "OK") {
                closeLayer()
                renderRoleTable()
                layer.msg("保存成功！")                     
            } else {
                if (res.code == 90001) {
                    layer.msg("本机构已存在相同英文名的角色！")
                    $("#enName").focus()
                }
            }
        },
        error: function (e) {
            console.log(e)
        }
    });
}

function renderTree() {
    var iTreeList = []
    var iVal

    if (objOrg) {
        iVal = JSON.stringify(objOrg).replace(/\"/g, "'")
        treeList.forEach(function (itree) {
            if (iVal == itree.value) {
                iTreeList.push(itree)
                return false
            }
        })
    }

    authtree.render(dst, iTreeList, {

        inputname: 'authids[]',
        checkType: 'checkbox',
        checkedArr: [],
        fgo: 0,
        flags: [1, 3, 5],
        layfilter: 'chkUser',
        openchecked: true,
        openall: false,
        autowidth: true
    });

    authtree.showDept(dst, 2);
}

function renderRoleTable() {

    table.reload('wfRole', {
        where: {
            orgId: objOrg? objOrg.orgId: null
        }
    });
}

function renderRoleUserTable() {
    // console.log(wfRoleUserList_obj)
    table.reload('wfRoleUser', {
        data: wfRoleUserList_obj
    });
}

//清空
function clearRoleUser() {
    wfRoleUserList_obj.length = 0
    wfRoleUserList_id.length = 0
    renderRoleUserTable()
    authtree.uncheckAll(dst)
}

//还原
function cancelRoleUser() {
    loadRoleUserData()
    renderRoleUserTable()
    renderTreeChecked()
}

//保存
function saveRoleUser() {
    if (!objOrg) {
        layer.msg("请选择机构！")
        return
    }else if (!objWfRole) {
        layer.msg("请选择角色！")
        return
    }

    $.ajax({
        url: "/wf-role-user/updateWfRoleUser",
        data: {
            wfRoleId: objWfRole.id,
            strIds: wfRoleUserList_id ? JSON.stringify(wfRoleUserList_id): null
        },
        type: 'post',
        success: function (res) {
            if (res.OK == "OK") {
                layer.msg("保存成功！")
            }
        },
        error: function (e) {
            console.log(e)
        }
    });

}

function disableTree() {
    $("#ouTree").find("input").attr("disabled", "ture")
    if(objOrg && !objWfRole) {
        $("#msgSelectRole").css("display", "")
    }

    form.render()
}

function enableTree() {
    $("#ouTree").find("input").removeAttr("disabled")
    $("#msgSelectRole").css("display", "none")
    form.render()
}

function loadRoleUserData() {
    clearRoleUser()
    if(!objWfRole) return

    $.ajax({
        url: "/wf-role-user/selectList",
        data: {
            wfRoleId: objWfRole.id
        },
        type: 'get',
        async: false,
        success: function (res) {
            if (res.OK == "OK") {
                res.List.forEach(function (iUser, i) {
                    if(wfRoleUserList_id.indexOf(iUser.id) < 0) {
                        wfRoleUserList_id.push(iUser.id)
                        wfRoleUserList_obj.push(iUser)
                    }
                })
            }
        },
        error: function (e) {
            console.log(e)
        }
    });

}

function renderTreeChecked() {

    wfRoleUserList_obj.forEach(function (iUser) {
        $("input[state='5'][title=" + iUser.name + "]").each(function (i, iDom) {
            var domId = parseInt($(iDom).val().replace(/^\{'id':([0-9]*),.*/, "$1"))
            if (domId == iUser.id) {
                $(iDom).click()
            }
        })
    })

    form.render()
}
